package com.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
    
    private static final DateTimeFormatter FORMATTER1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter FORMATTER2 = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
    
    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String dateString = p.getText().trim();
        if (dateString.isEmpty()) {
            return null;
        }
        
        // 尝试第一种格式
        try {
            return LocalDateTime.parse(dateString, FORMATTER1);
        } catch (DateTimeParseException e) {
            // 尝试第二种格式
            try {
                return LocalDateTime.parse(dateString, FORMATTER2);
            } catch (DateTimeParseException ex) {
                // 如果都不匹配，抛出异常
                throw new IOException("无法解析日期格式: " + dateString, ex);
            }
        }
    }
}